package com.luck.easyfoodbatch.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.igexin.sdk.PushManager;
import com.luck.easyfoodbatch.App;
import com.luck.easyfoodbatch.DemoHelper;
import com.luck.easyfoodbatch.R;
import com.luck.easyfoodbatch.db.DemoDBManager;
import com.luck.easyfoodbatch.ease.EaseCommonUtils;
import com.luck.easyfoodbatch.entity.User;
import com.luck.easyfoodbatch.mvp.mine.LoginModel;
import com.luck.easyfoodbatch.mvp.mine.LoginPresenter;
import com.luck.easyfoodbatch.mvp.mine.LoginView;
import com.luck.easyfoodbatch.mvp.mine.RegisterModel;
import com.luck.easyfoodbatch.mvp.mine.RegisterPresenter;
import com.luck.easyfoodbatch.mvp.mine.RegisterView;
import com.luck.easyfoodbatch.mvp.mine.SendVerificationModel;
import com.luck.easyfoodbatch.mvp.mine.SendVerificationPresenter;
import com.luck.easyfoodbatch.mvp.mine.SendVerificationView;
import com.luck.easyfoodbatch.mvp.model.RegModel;
import com.luck.easyfoodbatch.mvp.model.SendModel;
import com.luck.easyfoodbatch.mvp.model.UserModel;
import com.luck.easyfoodbatch.service.MessageService;
import com.luck.easyfoodbatch.util.HttpUtil;
import com.luck.easyfoodbatch.util.SharedPreferencesUtil;
import com.luck.easyfoodbatch.util.T;
import com.luck.easyfoodbatch.util.Tools;

import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class RegisterActivity extends BaseActivity implements RegisterView, SendVerificationView, LoginView {
    private static final String TAG = "LoginActivity";
    @BindView(R.id.et_tel)
    EditText etTel;
    @BindView(R.id.ll_del)
    LinearLayout llDel;
    @BindView(R.id.et_userName)
    EditText et_userName;
    @BindView(R.id.et_code)
    EditText etCode;
    @BindView(R.id.btn_sendCode)
    Button btnSendCode;
    @BindView(R.id.et_psw)
    EditText etPsw;
    @BindView(R.id.et_psw_again)
    EditText etPswAgain;
    @BindView(R.id.et_invite_code)
    EditText et_invite_code;
    @BindView(R.id.btn_register)
    Button btnRegister;
    @BindView(R.id.cb)
    CheckBox cb;
    @BindView(R.id.tv_http)
    TextView tv_http;
    private Timer tm;
    private TimerTask tk;
    private int count = 60;
    private RegisterModel registerModel;
    private SendVerificationModel verificationModel;
    private LoginModel loginModel;
    private Handler handler = new Handler();
    private Animation shake;
    private String typeName;
    private String groupId="1";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        typeName = getIntent().getStringExtra("typeName");
        setContentView(R.layout.activity_register, typeName, MODE_BACK_NAVIGATION);
        ButterKnife.bind(this);
        shake = AnimationUtils.loadAnimation(RegisterActivity.this, R.anim.shake);
        etTel.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.length() > 0) {
                    llDel.setVisibility(View.VISIBLE);
                } else {
                    llDel.setVisibility(View.GONE);
                }
            }
        });
        cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    btnRegister.setEnabled(true);
                    btnRegister.setTextColor(getResources().getColor(R.color.tab_color_true));
                    btnRegister.setBackgroundResource(R.drawable.btn_bg);
                } else {
                    btnRegister.setEnabled(false);
                    btnRegister.setTextColor(getResources().getColor(R.color.tab_color_false));
                    btnRegister.setBackgroundResource(R.drawable.btn_bg_false);
                }
            }
        });
    }

    @OnClick({R.id.ll_del, R.id.btn_sendCode, R.id.btn_register, R.id.tv_http, R.id.et_userName})
    public void onClick(View view) {
        reset();
        if (isFastDoubleClick()) {
            return;
        }
        String userName = et_userName.getText().toString().trim();
        String invite_code = et_invite_code.getText().toString().trim();
        String phone = etTel.getText().toString().trim();
        String psw = etPsw.getText().toString().trim();
        String code = etCode.getText().toString().trim();
        String pswAgain = etPswAgain.getText().toString().trim();
        switch (view.getId()) {
            case R.id.ll_del:
                etTel.setText("");
                break;
            case R.id.btn_sendCode:
                if (Tools.isNull(userName)) {
                    T.showToast(mContext, "请输入您的用户名");
                    et_userName.startAnimation(shake);
                } else if (Tools.isNull(phone)) {
                    T.showToast(mContext, "请输入您的手机号");
                    etTel.startAnimation(shake);
                } else if (!Tools.validatePhone(phone)) {
                    T.showToast(mContext, "请输入正确手机号");
                    etTel.startAnimation(shake);
                } else {
                    verificationModel = new SendVerificationPresenter(this, mContext);
                    verificationModel.sendSms(phone);
                    showProgressDialog("正在获取，请稍候……");
                    startCount();
                }
                break;
            case R.id.btn_register:
                if (Tools.isNull(userName)) {
                    T.showToast(mContext, "请输入您的用户名");
                    et_userName.startAnimation(shake);
                    et_userName.setBackgroundResource(R.drawable.shape_round_stroke_red);
                } else if (Tools.isNull(phone)) {
                    T.showToast(mContext, "请输入您的手机号");
                    etTel.startAnimation(shake);
                    etTel.setBackgroundResource(R.drawable.shape_round_stroke_red);
                } else if (!Tools.validatePhone(phone)) {
                    T.showToast(mContext, "请输入正确手机号");
                    etTel.startAnimation(shake);
                    etTel.setBackgroundResource(R.drawable.shape_round_stroke_red);
                } else if (Tools.isNull(code)) {
                    T.showToast(mContext, "请输入验证码");
                    etCode.startAnimation(shake);
                    etCode.setBackgroundResource(R.drawable.shape_round_stroke_red);
                } else if (Tools.isNull(psw)) {
                    T.showToast(mContext, "请输入您的密码");
                    etPsw.startAnimation(shake);
                    etPsw.setBackgroundResource(R.drawable.shape_round_stroke_red);
                } else if (psw.length() < 6) {
                    T.showToast(mContext, "密码长度不能小于6位");
                    etPsw.startAnimation(shake);
                    etPsw.setBackgroundResource(R.drawable.shape_round_stroke_red);
                } else if (Tools.isNull(pswAgain)) {
                    T.showToast(mContext, "请再次输入密码");
                    etPswAgain.startAnimation(shake);
                    etPswAgain.setBackgroundResource(R.drawable.shape_round_stroke_red);
                } else if (!psw.equals(pswAgain)) {
                    T.showToast(mContext, "两次密码输入不一致");
                    etPsw.startAnimation(shake);
                    etPswAgain.startAnimation(shake);
                    etPsw.setBackgroundResource(R.drawable.shape_round_stroke_red);
                    etPswAgain.setBackgroundResource(R.drawable.shape_round_stroke_red);
                } else {
                    showProgressDialog("正在注册，请稍候……");
                    registerModel = new RegisterPresenter(this, mContext);
                    registerModel.appRegister(invite_code, phone, code, psw);
//                    registerModel.appRegister(groupId,userName,invite_code,psw, pswAgain, phone, code);
                }
                break;
            case R.id.tv_http:
                Intent intent = new Intent(mContext, BaseHttpActivity.class);
                startActivity(intent);
                break;
            case R.id.et_userName:
                break;
        }
    }

    public void reset() {
        etCode.setBackgroundResource(R.drawable.shape_round_stroke_gray);
        etTel.setBackgroundResource(R.drawable.shape_round_stroke_gray);
        etPsw.setBackgroundResource(R.drawable.shape_round_stroke_gray);
        etPswAgain.setBackgroundResource(R.drawable.shape_round_stroke_gray);
    }

    /**
     * 启动时间器读秒
     */
    private void startCount() {
        tm = new Timer();
        tk = new TimerTask() {

            @Override
            public void run() {
                Message msg = mHandler.obtainMessage();
                count--;
                if (count > 0) {
                    msg.arg1 = count;
                    msg.what = 0;
                    msg.obj = count;
                    mHandler.sendMessage(msg);
                } else {
                    // 时间读完 初始秒数
                    mHandler.sendEmptyMessage(11);
                    count = 60;
                }

            }
        };
        tm.schedule(tk, 0, 1000);
    }

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    btnSendCode.setEnabled(false);
                    btnSendCode.setBackgroundResource(R.drawable.shape_round_solid_false_bg);
                    btnSendCode.setText(msg.arg1 + "秒");
                    btnSendCode.setTextColor(getResources().getColor(R.color.tab_color_false));
                    break;
                case 11:
                    btnSendCode.setEnabled(true);
                    btnSendCode.setBackgroundResource(R.drawable.shape_round_solid_bg);
                    btnSendCode.setText("发送验证码");
                    btnSendCode.setTextColor(getResources().getColor(R.color.white));
                    tk.cancel();
                    break;
            }
        }

    };

    @Override
    public void appRegisterSuccess(RegModel register) {
        if (register.getStatus() == HttpUtil.RESULT_OK) {
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    // 注册成功重新登录
                    showProgressDialog("正在登录，请稍候……");
                    loginHX(etTel.getText().toString().trim(), etPsw.getText().toString().trim());
                }
            }, 50);
        } else {
            T.showToast(mContext, register.getMsg());
        }
    }

    @Override
    public void loginSuccess(UserModel userModel) {
        if (userModel.getStatus() == HttpUtil.RESULT_OK) {
            T.showToast(mContext, userModel.getMsg());
            User data = userModel.getData();
            data.setAuthToken(userModel.getAuthToken());
            App.getInstance().saveObject(data, HttpUtil.USER_KEY);
            SharedPreferencesUtil.saveData(this, "mobile", data.getMobile());
            // 消息Service进行本地消息同步
            startService(new Intent(RegisterActivity.this, MessageService.class));
            sendBroadcast("action.app.refresh.mine");
            sendBroadcast("action.app.refresh.login");
            sendBroadcast("action.app.cart.refresh");
            setResult(RESULT_OK);
            finish();
        } else {
            T.showToast(mContext, userModel.getMsg());
        }
    }

    @Override
    public void httpStatusError() {
        T.showToast(mContext, getResources().getString(R.string.app_http_error));
    }


    @Override
    public void appSendSmsSuccess(SendModel sendModel) {
        if (sendModel.getStatus() == HttpUtil.RESULT_OK) {
            String code = sendModel.getData().getCode();
            T.showToast(mContext, sendModel.getMsg());
            etCode.requestFocus();
        } else {
            T.showToast(mContext, sendModel.getMsg());
        }
    }

    @Override
    public void hideLoading() {
        hideShowProgress();
    }

    /**
     * 登录环信
     *
     * @param currentUsername
     * @param currentPassword
     */
    public void loginHX(final String currentUsername, final String currentPassword) {
        if (!EaseCommonUtils.isNetWorkConnected(this)) {
            Toast.makeText(this, R.string.network_isnot_available, Toast.LENGTH_SHORT).show();
            return;
        }

        if (TextUtils.isEmpty(currentUsername)) {
            Toast.makeText(this, R.string.User_name_cannot_be_empty, Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(currentPassword)) {
            Toast.makeText(this, R.string.Password_cannot_be_empty, Toast.LENGTH_SHORT).show();
            return;
        }

        // After logout，the DemoDB may still be accessed due to async callback, so the DemoDB will be re-opened again.
        // close it before login to make sure DemoDB not overlap
        DemoDBManager.getInstance().closeDB();

        // reset current user name before login
        DemoHelper.getInstance().setCurrentUserName(currentUsername);

        final long start = System.currentTimeMillis();
        // call login method
        Log.d(TAG, "EMClient.getInstance().login");
        EMClient.getInstance().login(currentUsername + "_hx", "ysp123456", new EMCallBack() {

            @Override
            public void onSuccess() {
                Log.d(TAG, "login: onSuccess");
                EMClient.getInstance().chatManager().loadAllConversations();
                // update current user's display name for APNs
                boolean updatenick = EMClient.getInstance().updateCurrentUserNick(
                        App.currentUserNick.trim());
                if (!updatenick) {
                    Log.e("LoginActivity", "update current user nick fail");
                }
                // 环信登录成功，在登录本地
                loginModel = new LoginPresenter(RegisterActivity.this, mContext);
                loginModel.appLogin(currentUsername, currentPassword, PushManager.getInstance().getClientid(RegisterActivity.this));
//                loginModel.appLogin(currentUsername, currentPassword);
            }

            @Override
            public void onProgress(int progress, String status) {
                Log.d(TAG, "login: onProgress");
            }

            @Override
            public void onError(final int code, final String message) {
                Log.d(TAG, "login: onError: " + code);
                runOnUiThread(new Runnable() {
                    public void run() {
                        Toast.makeText(getApplicationContext(), getString(R.string.Login_failed) + message,
                                Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }
}
